package com.zk.ppa.controller;

import com.alibaba.fastjson.JSONObject;
import com.zk.ppa.commom.exception.BaseException;
import com.zk.ppa.commom.exception.BaseRuntimeException;
import com.zk.ppa.commom.result.Result;
import com.zk.ppa.controller.vo.in.LoginInVO;
import com.zk.ppa.controller.vo.out.ProfileOutVO;
import com.zk.ppa.service.AuthService;
import com.zk.ppa.service.dto.in.LoginDTO;
import com.zk.ppa.service.dto.out.ProfileOutDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chenxiaolong
 * @since 2021年03月21日 13:15:00
 */
@RestController
@Api(value = "登录功能接口", tags = {"登录功能接口"})
@Slf4j
@CrossOrigin
public class AuthController {

    @Autowired
    private AuthService authService;

    @GetMapping("/code/{uuid}")
    @ApiOperation(value = "获取验证码接口", notes = "获取验证码接口")
    public void code(HttpServletResponse response, @PathVariable("uuid") String uuid){
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            String code = authService.createCode(uuid, outputStream);
            log.info("请求到的验证码：{}", code);
            outputStream.close();
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException("输出流错误");
        }

    }

    @PostMapping("/login")
    @ApiOperation(value = "登录接口", notes = "登录接口")
    public Result<String> login(@Validated @RequestBody LoginInVO inVO) throws BaseException {
        log.info("登录的参数：{}", JSONObject.toJSON(inVO));
        LoginDTO loginDTO = new LoginDTO();
        loginDTO.setAccount(inVO.getAccount())
                .setCode(inVO.getCode())
                .setPassword(inVO.getPassword())
                .setUuid(inVO.getUuid());
        String token = null;
        try {
            token = authService.login(loginDTO);
        } catch (BaseException e) {
            log.error(e.getMessage());
            throw e;
        }
        return Result.SUCCESS().setData(token);
    }

    @GetMapping("/profile")
    @ApiOperation(value = "获取登录用户信息", notes = "获取登录用户信息")
    public Result<ProfileOutVO> profile(HttpServletRequest request){
        String tokenHeader = request.getHeader("Authorization");
        log.info("tokenHeader: {}", tokenHeader);
        if(tokenHeader == null || tokenHeader.isEmpty()){
            throw new BaseRuntimeException("请求有误");
        }

        String token = tokenHeader.replace("Bearer ", "");
        ProfileOutDTO profile = authService.getProfile(token);
        ProfileOutVO profileOutVO = new ProfileOutVO();
        profileOutVO.setAccount(profile.getAccount())
                .setId(profile.getId())
                .setName(profile.getName())
                .setPassword(profile.getPassword())
                .setRole(profile.getRole())
                .setUnit(profile.getUnit());

        return Result.SUCCESS().setData(profileOutVO);
    }
}
